<?php
session_start();

// 用户直接点击进入此页面将强制跳转到主页
if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

// 已登录的用户可以回复
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    // 获取回复内容和问题ID
    $content = trim($_POST['content']);
    $questionId = isset($_POST['question_id']) ? intval($_POST['question_id']) : 0;

    // 验证回复内容是否为空
    if (empty($content)) {
        echo "<div class='alert alert-danger'>回复内容不能为空！</div>";
    } else {
        // 连接数据库
        $host = 'localhost';
        $db   = 'dev_community';
        $user = 'root'; // 请替换为您的数据库用户名
        $pass = 'root'; // 请替换为您的数据库密码
        $charset = 'utf8mb4';

        $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];

        try {
            $pdo = new PDO($dsn, $user, $pass, $options);
        } catch (\PDOException $e) {
            die("数据库连接失败: " . $e->getMessage());
        }

        // 检查question_id是否存在于questions表中
        $stmt = $pdo->prepare("SELECT id FROM questions WHERE id = ?");
        $stmt->execute([$questionId]);
        if (!$stmt->fetch()) {
            // 如果没有找到对应的question_id，显示错误消息并退出
            die("无效的问题ID。");
        }

        // 插入回复到数据库
        try {
            $stmt = $pdo->prepare("INSERT INTO answers (question_id, user_id, content) VALUES (?, ?, ?)");
            $stmt->execute([$questionId, $_SESSION['user_id'], $content]);

            // 更新问题浏览次数
            $pdo->exec("UPDATE questions SET view_count = view_count + 1 WHERE id = $questionId");

            // 重定向回查看帖子的页面，或者显示成功消息
            header('Location: viewPost.php?id=' . $questionId);
            exit;
        } catch (\PDOException $e) {
            echo "<div class='alert alert-danger'>数据库操作失败: " . $e->getMessage() . "</div>";
        }
    }
}
?>

<html>
<head>
<meta charset="utf-8">
<title>智界论坛-回复</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
</head>
<body>
    <div class="panel">
        <div class="panel-heading" style="background-color: #00000008; border-bottom: solid 1px #00000016;"><h2 style="text-align:left; margin-left: 360px; font-size: 22px;">PHP开放社区</h2></div>
        <div class="row" style="margin: 30px;">
            <div class="col-md-8 col-md-offset-2" style="margin-top: 60px; border: solid 1px orange;">
                <h3 style="text-align: center;">发表回复</h3>
                <form method="post" action="" enctype="multipart/form-data">
                    <input type="hidden" name="question_id" value="<?php echo isset($_GET['id']) ? intval($_GET['id']) : ''; ?>">
                    <p style="padding-left:70px;">内容：<textarea name="content" rows="5" cols="90" required></textarea></p>
                    <p><input class="btn btn-primary" style="float:right; margin-bottom:20px;" type="submit" value="提交" name="submit"></p>
                </form>
            </div>
        </div>
        <div class="col-md-1 col-md-offset-8">
            <a href="index.php" style="font-size: 16px; padding-bottom:30px;">返回主页</a>
        </div>
    </div>


       <!-- 添加网页尾部 -->
       <div class="footer">
        <p>&copy;  智界论坛·保留所有权利</p>
        <p>版权所有☆Qualan<sup>&copy;</sup> Q_L</p>
        </div>
</body>
</html>